//
//  emotionViewController.swift
//  emotionKeyBoard
//
//  Created by 路峻鉴 on 15/10/17.
//  Copyright © 2015年 路峻鉴. All rights reserved.
//

import UIKit
///表情cell标示符
private let emotionCell = "emotionCell"

class emotionViewController: UIViewController {
    ///选择表情的回调
    var selectedEmotionCallBack: (emotion: Emotion) -> ()
    init(selectedEmotion: (emotion: Emotion) -> ()) {
        selectedEmotionCallBack = selectedEmotion
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
    }
    //MARK: ************搭建界面**********
    private func setUpUI() {
        // 添加空件
        view.addSubview(toolBar)
        view.addSubview(collectionView)
        //设置自动布局
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        let viewDic = ["CV": collectionView, "TB": toolBar]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[CV]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[TB]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[CV]-0-[TB(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic))
        
        //设置布局
        prepareToolBar()
        prepareCollection()
    }
    //MARK: ************准备toolBar布局**********
    func clickToolBarItem(item: UIBarButtonItem) {
        let index = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    ///准备toolBar布局
    private func prepareToolBar() {
        toolBar.tintColor = UIColor.darkGrayColor()
        var item = [UIBarButtonItem]()
        var indet = 0
        for arr in ["最近", "默认", "emoji", "浪小花"] {
            item.append(UIBarButtonItem(title: arr, style: UIBarButtonItemStyle.Plain, target: self, action: "clickToolBarItem:"))
            item.last?.tag = indet++
            item.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        item.removeLast()
        toolBar.items = item
    }
    //MARK: ************准备collection布局*********
    ///准备collection布局
    private func prepareCollection() {
        collectionView.registerClass(EmotionCell.self, forCellWithReuseIdentifier: emotionCell)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    //MARK: ************懒加载控件**********
    ///表情包
    lazy private var packages = emotionPackage.packages()
    lazy private var toolBar = UIToolbar()
    lazy private var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: LJJEmotionLayout())
    class LJJEmotionLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            super.prepareLayout()
            let w = collectionView!.bounds.width / 7.0
            let y = (collectionView!.bounds.height - 3 * w) * 0.499
            itemSize =  CGSize(width: w, height: w)
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

extension emotionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    //MARK: ************代理方法**********
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emotion = packages[indexPath.section].emoticons![indexPath.item]
        selectedEmotionCallBack(emotion: emotion)
    }
    //MARK: ************数据源方法**********
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons!.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emotionCell, forIndexPath: indexPath) as! EmotionCell
        cell.emotion = packages[indexPath.section].emoticons![indexPath.item]
        return cell
    }
}

///表情cell
private class EmotionCell: UICollectionViewCell {
    ///表情
    var emotion: Emotion? {
        didSet {
            emotionButton.setImage(UIImage(contentsOfFile: emotion!.imagePath), forState: UIControlState.Normal)
            emotionButton.setTitle(emotion!.emoji, forState: UIControlState.Normal)
            if emotion!.removeEmoticon {
                emotionButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emotionButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.orangeColor()
        emotionButton.backgroundColor = UIColor.whiteColor()
        emotionButton.frame = CGRectInset(bounds, 4, 4)
        //调整emoji大小
        emotionButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        //禁用按钮,让cell交互
        emotionButton.userInteractionEnabled = false
        addSubview(emotionButton)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var emotionButton: UIButton = UIButton()
}
